﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YiShi.Class;
using AcsCommon;
using System.Threading;
using System.Data;
using System.Collections.ObjectModel;
using Microsoft.JScript;

namespace YiShi.Question
{
    public partial class QuestionEdit : System.Web.UI.Page
    {
        private string guideLinkTemplate = @"
        <div {0} style='width: 100%;'>
            <table style='width: 100%; border-collapse: collapse;' class='single-border'>
                <tr class='table-body' align='left'>
                    <td>
                        <table style='width: 100%; border-collapse: collapse;' class='single-border'>
                            <tr class='table-body' style='height: 29px;'>
                                <td style='width: 100px;' align='center' class='single-border'>
                                    选择的答案
                                </td>
                                <td class='single-border' align='left'>
                                    <input name='Answer' type='text' style='width: 100px;' value='{1}'/>
                                </td>
                                <td class='single-border' align='center' style='width: 20px;'>
                                    <button name='ExpandButton' style='font-size: 0pt;'>
                                        <span class='ui-icon ui-icon-minusthick'></span>
                                    </button>
                                </td>
                            </tr>
                            <tr class='table-body'>
                                <td align='center' class='single-border'>
                                    对应的提示
                                </td>
                                <td class='single-border' align='left' colspan='2'>
                                    <textarea name='Tip' cols='20' rows='2' style='width: 99%; height: 100px;'>{2}</textarea>
                                </td>
                            </tr>
                            <tr class='table-body'>
                                <td align='center' class='single-border'>
                                    对应的知识点
                                </td>
                                <td class='single-border' align='left' colspan='2'>
                                    <input name='KnowledgePointIds' type='hidden' value='{3}'/>
                                    <input name='KnowledgePointNames' type='text' style='width: 200px;' value='{4}'/>
                                    <button style='font-size: 0pt;' name='KnowledgePointMultiSelectButton'>
                                        <span class='ui-icon ui-icon-newwin'></span>
                                    </button>
                                </td>
                            </tr>
                            <tr class='table-body'>
                                <td align='center' class='single-border'>
                                    下一步导向
                                </td>
                                <td class='single-border' align='left' colspan='2'>
                                    <select name='NextGuideId'>
                                        <option value='_New'>新建引导</option>
                                        {5}
                                        <option value='00000000'>结束</option>
                                    </select>
                                    <span style='display: none;'>新建引导名称<input name='Name' type='text' style='width: 100px;' />
                                    </span>
                                </td>
                            </tr>
                            <tr class='table-body'>
                                <td align='center' class='single-border'>
                                    操作
                                </td>
                                <td class='single-border' align='left' colspan='2'>
                                    <button name='InsertLink' guidelinkid='{6}'>
                                        保存</button>
                                    <button name='DeleteLink'>
                                        删除</button>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td align='center' name='AnswerArea'>
                        {7}
                    </td>
                </tr>
            </table>
        </div>";
        private string guideTemplate = @"
        <div {0} style='width: 100%;'>
            <table style='width: 100%; border-collapse: collapse;' class='single-border'>
                <tr class='table-body' align='left'>
                    <td>
                        <table style='width: 100%; border-collapse: collapse;' class='single-border'>
                            <tr style='height: 29px;'>
                                <td style='width: 100px;' align='center'>
                                    引导问题名称
                                </td>
                                <td align='left'>
                                    <input name='Name' type='text' disabled value='{1}'/>
                                </td>
                                <td class='single-border' align='center' style='width: 20px;'>
                                    <button name='ExpandButton' style='font-size: 0pt;'>
                                        <span class='ui-icon ui-icon-minusthick'></span>
                                    </button>
                                </td>
                            </tr>
                        </table>
                        <table style='width: 100%; border-collapse: collapse;'>
                            <tr>
                                <td style='width: 100px;' align='center' class='single-border'>
                                    问题
                                </td>
                                <td class='single-border' colspan='2' align='center'>
                                    <div name='Body' style='overflow:auto;text-align: left; width: 99%; height: 100px; background-color: White;'>
                                        {2}</div>
                                    <button name='Edit'>
                                        编辑</button>
                                </td>
                            </tr>
                            <tr>
                                <td align='center' class='single-border'>
                                    类型
                                </td>
                                <td class='single-border' colspan='2'>
                                    {3}
                                </td>
                            </tr>
                            <tr>
                                <td align='center' class='single-border'>
                                    答案
                                </td>
                                <td class='single-border'>
                                    <input name='Answer' type='text' value='{4}' />(以"",""号分隔)
                                </td>
                            </tr>
                            <tr>
                                <td align='center' class='single-border'>
                                    操作
                                </td>
                                <td class='single-border' colspan='2'>
                                    <button name='Save' guideid='{5}'>
                                        保存</button>
                                    <button name='Delete'>
                                        删除</button>
                                    {6}
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td align='center' name='AnswerArea'>
                        {7}
                    </td>
                </tr>
            </table>
        </div>";
        DbAccess db;
        DbEnum de;
        protected string id;
        protected string body;
        protected string typeHtml;
        protected string answer;
        protected string scores;
        protected string answerArea;
        protected string insertGuideLink;
        protected string guideLinkHtml;
        protected string guideHtml;
        Collection<Guide> guides;
        Collection<Guide> enumGuides;
        Collection<GuideLink> links;

        public QuestionEdit()
        {
            this.db = DbAccess.Get("Admin");
            de = DbEnum.Get(this.db, "Question.Type");
            guides = new Collection<Guide>();
            enumGuides = new Collection<Guide>(); ;
            links = new Collection<GuideLink>();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            JsonObject jo = new JsonObject();
            try
            {
                string action = Request["ActionType"] == null ? "" : Request["ActionType"];
                switch (action.ToLower())
                {
                    case "dataupdate":
                        DataUpdate();
                        break;
                    case "insertguidelink":
                    case "updateguidelink":
                        jo = UpdateGuideLink();
                        break;
                    case "insertmainguide":
                        jo = InsertMainGuide();
                        break;
                    case "deleteguidelink":
                        jo = DeleteGuideLink();
                        break;
                    case "insertguide":
                    case "updateguide":
                        jo = UpdateGuide();
                        break;
                    case "deleteguide":
                        jo = DeleteGuide();
                        break;
                    case "insert":
                    case "update":
                        jo = Update();
                        break;
                    case "selectget":
                        jo = SelectGet();
                        break;
                    default:
                        DataInsert();
                        break;
                }
            }
            catch (Exception e1)
            {
                jo.Add("IsSuccess", "false");
                jo.Add("Message", e1.Message);
                jo.Add("Source", e1.Source);
                jo.Add("StackTrace", e1.StackTrace);
            }
            finally
            {
                if (jo.Count > 0)
                {
                    Response.Write(jo.ToString().Replace("'", "\""));
                    Response.End();
                }
            }
        }
        private void DataUpdate()
        {
            id = this.Request["Id"];
            Class.Question q = new YiShi.Class.Question(db);
            q.FillFromDb(id);
            body = Utility.HtmlDecode(GlobalObject.unescape(q.Body));
            answer = q.Answer;
            scores = q.Scores;
            typeHtml = Utility.GetSelectHtml(de, "Type", q.Type);
            
            string sql = Sql.Format("select * from Guide where (QuestionId = '{0}') order by Id", id);
            DataTable dt = db.QueryDataTable(sql);
            string mainguideid = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Guide guide = new Guide(db);
                dt.Rows[i].FillObject(guide);
                if (guide.Name == "主引导")
                    mainguideid = guide.Id;
                guides.Add(guide);
                enumGuides.Add(guide);
            }
            insertGuideLink = String.Format("<button name='InsertMainGuide' {0}>新增主引导</button>", dt.Rows.Count > 0 ? "disabled" : "");
            GenerateTemplateHtml();
            sql = Sql.Format("select * from GuideLink where (QuestionId = '{0}') order by Id", id);
            dt = db.QueryDataTable(sql);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                GuideLink link = new GuideLink(db);
                dt.Rows[i].FillObject(link);
                links.Add(link);
            }

            answerArea = GetGuide(mainguideid);
        }
        private string GetEnumhtml(string guideId)
        {
            string enumhtml = "";
            foreach (Guide g in enumGuides)
            {
                string selected = g.Id == guideId ? "selected" : "";
                enumhtml += String.Format("<option value='{0}' {1}>{2}</option>", g.Id, selected, g.Name);
            }
            return enumhtml;
        }
        private string GetGuideLink(string guideId)
        {
            string html = "";
            foreach (GuideLink link in links)
            {
                if (link.PreGuideId == guideId)
                {

                    html += String.Format(guideLinkTemplate, "", link.Answer, link.Tip, link.KnowledgePointIds, link.KnowledgePointNames, GetEnumhtml(link.NextGuideId), link.Id, GetGuide(link.NextGuideId));
                }
            }
            return html;
        }
        private void GenerateTemplateHtml()
        {
            guideLinkHtml = String.Format(guideLinkTemplate, "id='GuideLinkTemplate'", "", "", "", "", GetEnumhtml(null), "", "");
            guideHtml = String.Format(guideTemplate, "id='GuideTemplate'", "", "", Utility.GetSelectHtml(de, "Type"), "", "", "", "");
        }
        private void DataInsert()
        {
            typeHtml = Utility.GetSelectHtml(de, "Type");
            guideLinkHtml = String.Format(guideLinkTemplate, "id='GuideLinkTemplate'", "", "", "", "", "", "", "");
            guideHtml = String.Format(guideTemplate, "id='GuideTemplate'", "", "", typeHtml, "", "", "", "");
        }
        private string GetGuide(string guideId)
        {
            foreach (Guide guide in guides)
            {
                if (guide.Id == guideId)
                {
                    guides.Remove(guide);
                    return String.Format(guideTemplate, "", guide.Name, Utility.HtmlDecode(GlobalObject.unescape(guide.Body)), Utility.GetSelectHtml(de, "Type", guide.Type), guide.Answer, guideId, "<button name='InsertGuideLink'>新增选项提示</button>", GetGuideLink(guideId));
                }
            }
            return "";
        }
        private JsonObject SelectGet()
        {
            string sql = "select Id, Name from Guide where (QuestionId = '{0}') order by Id";
            sql = Sql.Format(sql, Request["Id"]);
            DataTable dt = this.db.QueryDataTable(sql);
            string template = "<option value={0}>{1}</option>";
            string html = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                html += String.Format(template, dr.GetValue("Id"), dr.GetValue("Name"));
            }
            JsonObject jo = new JsonObject();
            jo.Add("IsSuccess", "true");
            jo.Add("Html", html);
            return jo;
        }
        private JsonObject DeleteGuideLink()
        {
            JsonObject jo = new JsonObject();

            GuideLink link = new GuideLink(db);
            link.Id = Request["Id"];
            link.Delete();
            jo.Add("IsSuccess", "true");
            return jo;
        }
        private JsonObject InsertMainGuide()
        {
            JsonObject jo = new JsonObject();
            Guide g = new Guide(db);
            g.Name = Request["Name"];
            g.Update();
            jo.Add("NextGuideId", g.Id);
            jo.Add("IsSuccess", "true");
            return jo;
        }
        private JsonObject UpdateGuideLink()
        {
            JsonObject jo = new JsonObject();

            GuideLink link = new GuideLink(db);
            link.Fill(Request);
            if (Request["NextGuideId"] == "_New")
            {
                Guide g = new Guide(db);
                g.Name = Request["Name"];
                g.Update();
                jo.Add("NextGuideId", g.Id);
                link.NextGuideId = g.Id;
            }
            link.Update();
            jo.Add("IsSuccess", "true");
            jo.Add("Id", link.Id);
            return jo;
        }
        private JsonObject DeleteGuide()
        {
            JsonObject jo = new JsonObject();
            Guide g = new Guide(db);
            g.Id = Request["Id"];
            g.Delete();
            jo.Add("IsSuccess", "true");
            return jo;
        }
        private JsonObject UpdateGuide()
        {
            JsonObject jo = new JsonObject();
            Guide g = new Guide(db);
            g.Fill(Request);
            g.Update();
            jo.Add("IsSuccess", "true");
            jo.Add("Id", g.Id);
            return jo;
        }
        private JsonObject Update()
        {
            JsonObject jo = new JsonObject();
            YiShi.Class.Question question = new YiShi.Class.Question(db);
            question.Fill(Request);
            question.Update();
            jo.Add("IsSuccess", "true");
            jo.Add("Id", question.Id);
            return jo;
        }
    }
}
